# -*- coding: utf-8 -*-
module JpMailer::Mobile::Au

  def self.match_recipient?(recipient)
    /(.*?)<(.*?)>/ =~ recipient
    scanner.match($& ? $2 : recipient) ? true : false
  end

  # 文字コードを指定
  def self.extended(receiver)
    receiver.instance_variable_set(:@charset, 'iso-2022-jp')
    if receiver.enabled_emotion_conversion?
      receiver.instance_variable_set(:@emotion_conversion_table, Jpmobile::Emoticon::CONVERSION_TABLE_TO_AU)
    end
    receiver.extend JpMailer::Mobile::Base
  end

  private
  def self.scanner
    /ezweb\.ne\.jp\z/
  end

  public
  def enabled_emotion_conversion?
    defined? Jpmobile::Emoticon ? true : false
  end

  # SJISからJISに
  def convert_sjis2jis(sjisstr)
    buf = ''
    dst = ''
    src = sjisstr.unpack('C*')
    
    idx = 0
    while idx < src.size
      c1 = src[idx]
      c2 = 0
      
      # SJIS の場合
      # 0x00 - 0x7F ascii
      # 0xA1 - 0xDF 1byte(半角カナ)
      # それ以外    2byte
      if (c1 >= 0x80 && (c1 < 0xA1 || 0xDF < c1) && idx+1 < src.size)
        c2 = src[idx = idx.succ]
      end
      
      # 絵文字かどうか
      if ( (0xF3 == c1 && 0x40 <= c2 && c2 <= 0xFC && c2 != 0x7F) ||
           (0xF4 == c1 && 0x40 <= c2 && c2 <= 0x8D && c2 != 0x7F) ||
           (0xF6 == c1 && 0x40 <= c2 && c2 <= 0xFC && c2 != 0x7F && c2 != 0xBE && c2 != 0xBF) ||
           (0xF7 == c1 && 0x40 <= c2 && c2 <= 0xFC && 
            c2 != 0x7F && c2 != 0x95 && c2 != 0xE2 && c2 != 0xE3 && c2 != 0xE4) 
           )
        # 絵文字
        
        # バッファをJISに変換してdstに追加
        unless buf.empty?
          dst << NKF.nkf('-Sj --cp932 -x', buf)
          buf = ''
        end
      
        # 絵文字をメール送出用SJISに変換
        c1 = case c1
             when 0xF6
               0xEB
             when 0xF7
               0xEC
             when 0xF3
               0xED
             when 0xF4
               0xEE
             else
               c1
             end
        dst << NKF.nkf('-Sjx', [c1, c2].pack('C*'))
      else
        # 絵文字以外
        buf << c1.chr
        buf << c2.chr if c2 > 0
      end
      idx = idx.succ
    end

    dst << NKF.nkf('-Sj --cp932 -x', buf) unless buf.empty?

    return dst
  end

end
